<template>
  <div>
    <div ref="echartsBar" class="bar_chart"></div>
  </div>
</template>
<script>
import * as echarts from 'echarts';
import {getUserWords} from '@/api/api'
export default {
  name: "homepageAds-index",
  data(){
    return{
      userName:[],
      allList:[],
      numList:[]
    }
  },
  mounted() {
        getUserWords().then((response) => {
          console.log('echarts',response.data)
            this.allList=response.data
            this.allList.map(item=>{
            this.userName.push(item.userName);
             this.userName= this.userName.slice(0, 7)
            this.numList.push(item.total);
               this.numList= this.numList.slice(0, 7)
          })
          console.log(' this.userName', this.userName)
          console.log(' this.total', this.numList)
             this.renderChart();
      })
  },
  components: {
  },
  methods: {
    renderChart() {
      // 初始化 echarts 实例
      const myChart = echarts.init(this.$refs.echartsBar);
  myChart.setOption({
           title: {
          text: '背单词榜前七',
          textStyle: {
            color: '#333', // 标题文字颜色
            fontSize: 18, // 标题文字大小
            fontWeight: 'bold' // 标题文字粗细
          }
        },
        xAxis: {
          type: 'category',
          data: this.userName,
          axisLabel:{
            interval:0,
            rotate:45
          },
          axisTick:{
            alignWithLabel:true
          }
        },
        yAxis: {
          type: 'value'
          
        },
        series: [
          {
                  data:this.numList,
                  type: 'bar',
                  label: {
                  normal: {
                    show: true,//开启显示
                    position: 'top',//柱形上方
                    textStyle: { //数值样式
                      color: '#000'
                    }
                  }
                }
            
          }
        ]

           })
 
      // 监听图表元素的点击事件
      myChart.on('click', (params) => {
        // 当点击柱状图的柱子时，params 包含点击元素的信息
        if (params.componentType === 'series' && params.seriesType === 'bar') {
          const dataIndex = params.dataIndex; // 获取点击的数据索引
          const dataValue = params.value; // 获取点击的数据值
          const dataName = params.name; // 获取点击的数据名称
 
          // 显示弹窗
          alert(`点击了用户${dataName}，其背的单词总数为${dataValue}`);
        }
      });
    }
  }
}
</script>
 
 
<style scoped>
.bar_chart {
  width: 60vw;
  height: 70vh;
}
</style>